<template>
  <div class="doctor-review">
    <h1>医生审核界面</h1>
    
    <div class="review-info">
      <p>以下是完整的药物相互作用分析报告，供医生审核和决策参考。</p>
    </div>
    
    <div class="report-section">
      <h2>患者基本信息</h2>
      <div class="report-content">
        <p><strong>年龄:</strong> {{ patientInfo.age }}岁</p>
        <p><strong>体重:</strong> {{ patientInfo.weight }}kg</p>
        <p><strong>性别:</strong> {{ genderMap[patientInfo.gender] || patientInfo.gender }}</p>
        <p><strong>肝功能:</strong> {{ liverFunctionMap[patientInfo.liverFunction] || patientInfo.liverFunction }}</p>
        <p><strong>肾功能:</strong> {{ kidneyFunctionMap[patientInfo.kidneyFunction] || patientInfo.kidneyFunction }}</p>
        <p><strong>药物过敏史:</strong> {{ patientInfo.allergies.length > 0 ? patientInfo.allergies.join(', ') : '无' }}</p>
      </div>
    </div>
    
    <div class="report-section">
      <h2>药物清单</h2>
      <div class="report-content">
        <ul>
          <li v-for="medication in medications" :key="medication.id">
            <strong>{{ medication.name }}</strong> |
            剂量: {{ medication.dosage }} |
            频次: {{ medication.frequency }} |
            途径: {{ medication.route }}
          </li>
        </ul>
      </div>
    </div>
    
    <div class="report-section" v-for="interaction in interactions" :key="interaction.id">
      <h2>药物相互作用分析</h2>
      <div class="report-content">
        <div class="interaction-item">
          <h3>{{ getSeverityText(interaction.severity) }}相互作用</h3>
          <p><strong>涉及药物:</strong> {{ interaction.drugs.join(' + ') }}</p>
          <p><strong>风险描述:</strong> {{ interaction.description }}</p>
          <p><strong>风险等级:</strong> <span :class="`risk-${interaction.severity.toLowerCase()}`">{{ getSeverityText(interaction.severity) }}</span></p>
          <p><strong>处理建议:</strong> {{ interaction.recommendation }}</p>
          
          <!-- AI深度分析结果显示 -->
          <div v-if="interaction.aiAnalysis">
            <div v-if="interaction.aiAnalysis.includes('### 药物相互作用分析报告')">
              <!-- 提取并显示药物相互作用机制 -->
              <div v-if="extractSection(interaction.aiAnalysis, '相互作用机制')">
                <h4>药物相互作用机制</h4>
                <div v-html="formatExtractedSection(extractSection(interaction.aiAnalysis, '相互作用机制') || '')"></div>
              </div>
              
              <!-- 提取并显示处理措施 -->
              <div v-if="extractSection(interaction.aiAnalysis, '处理措施')">
                <h4>临床处理措施</h4>
                <div v-html="formatExtractedSection(extractSection(interaction.aiAnalysis, '处理措施') || '')"></div>
              </div>
              
              <!-- 提取并显示药物替换建议 -->
              <div v-if="extractSection(interaction.aiAnalysis, '药物替换')">
                <h4>药物替换建议</h4>
                <div v-html="formatExtractedSection(extractSection(interaction.aiAnalysis, '药物替换') || '')"></div>
              </div>
            </div>
            <div v-else>
              <h4>AI深度分析结果</h4>
              <div class="ai-analysis-content" v-html="formatAiAnalysis(interaction.aiAnalysis)"></div>
            </div>
          </div>
          
          <!-- 未分析提示 -->
          <div v-else class="not-analyzed">
            <div v-if="(interaction.severity.toLowerCase() === 'high' || interaction.severity.toLowerCase() === 'medium')">
              <p>暂未进行分析</p>
            </div>
            <div v-else>
              <p>根据现有信息，当前用药方案相对安全</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="action-buttons">
      <button @click="printReport" class="print-btn">打印报告</button>
      <button @click="exportReport" class="export-btn">导出PDF</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive } from 'vue'
// @ts-ignore
import { useStore } from 'vuex'
import { analyzeDrugInteractionWithSparkHttp } from '@/services/index'
import { tencentTranslateService } from '@/services/index'

const store = useStore()

// 获取患者信息
const patientInfo = computed(() => store.state.patientInfo)

// 获取药物清单
const medications = computed(() => store.state.medications)

// 获取相互作用数据
const interactions = computed(() => {
  // 创建响应式副本以便我们可以添加加载状态
  return reactive(store.state.interactions.map((interaction: any) => ({
    ...interaction,
    aiAnalysisLoading: false
  })))
})

// 获取高风险相互作用
const highRiskInteractions = computed(() => {
  return interactions.value.filter((interaction: any) => interaction.severity === 'high')
})

// 性别映射
const genderMap: Record<string, string> = {
  male: '男',
  female: '女',
  other: '其他'
}

// 肝功能映射
const liverFunctionMap: Record<string, string> = {
  normal: '正常',
  mild: '轻度异常',
  moderate: '中度异常',
  severe: '重度异常'
}

// 肾功能映射
const kidneyFunctionMap: Record<string, string> = {
  normal: '正常',
  mild: '轻度异常',
  moderate: '中度异常',
  severe: '重度异常'
}

// 获取风险等级文本
const getSeverityText = (severity: string) => {
  switch (severity.toLowerCase()) {
    case 'high': return '高风险'
    case 'medium': return '中风险'
    case 'low': return '低风险'
    case 'unknown': return '未知风险'
    default: return '未知风险'
  }
}

// 格式化AI分析结果
const formatAiAnalysis = (content: string) => {
  if (!content) return ''
  
  // 将换行符转换为<br>标签
  return content.replace(/\n/g, '<br>')
}

// 提取AI分析的特定部分
const extractSection = (content: string, sectionTitle: string) => {
  if (!content) return null
  
  // 创建正则表达式匹配章节标题
  const sectionRegex = new RegExp(`####\\s*${sectionTitle}[\\s\\S]*?(?=####|$)`, 'g')
  const match = sectionRegex.exec(content)
  
  if (match) {
    // 移除标题行并返回内容
    return match[0].replace(`#### ${sectionTitle}`, '').trim()
  }
  
  return null
}

// 格式化提取的内容
const formatExtractedSection = (content: string) => {
  if (!content) return ''
  
  // 移除多余的换行和格式化内容
  let formatted = content
    .replace(/\n\n/g, '</p><p>')  // 将双换行转换为段落
    .replace(/\n/g, '<br>')       // 将单换行转换为换行标签
    .replace(/^- /gm, '• ')       // 将列表符号转换为HTML符号
  
  // 如果内容不以p标签开头，则添加
  if (!formatted.startsWith('<p>')) {
    formatted = '<p>' + formatted + '</p>'
  }
  
  return formatted
}

// 执行AI分析
const performAIAnalysis = async (interaction: any) => {
  // 设置加载状态
  interaction.aiAnalysisLoading = true
  
  try {
    // 构建患者特征信息
    const patientFeatures = `
      年龄: ${patientInfo.value.age}岁,
      体重: ${patientInfo.value.weight}kg,
      性别: ${genderMap[patientInfo.value.gender] || patientInfo.value.gender},
      肝功能: ${liverFunctionMap[patientInfo.value.liverFunction] || patientInfo.value.liverFunction},
      肾功能: ${kidneyFunctionMap[patientInfo.value.kidneyFunction] || patientInfo.value.kidneyFunction},
      药物过敏史: ${patientInfo.value.allergies.length > 0 ? patientInfo.value.allergies.join(', ') : '无'}
    `.replace(/\s+/g, ' ').trim()
    
    // 构建分析提示
    const prompt = `
      作为一名专业的临床药师，请基于以下患者特征和药物相互作用信息，提供一份高度个性化的详细分析报告。
      
      ### 患者特征（非常重要，请重点考虑这些因素）：
      ${patientFeatures}
      
      ### 药物相互作用信息：
      涉及药物: ${interaction.drugs.join(' + ')}
      风险描述: ${interaction.description}
      风险等级: ${getSeverityText(interaction.severity)}
      处理建议: ${interaction.recommendation}
      
      ### 分析要求：
      请根据上述患者特征和药物相互作用信息，提供以下内容的详细分析：
      
      1. 相互作用机制：详细解释药物之间如何相互作用，特别考虑患者的年龄、性别、体重、肝肾功能等个体差异对药物代谢的影响。
      2. 临床风险评估：评估该相互作用对这位特定患者的实际风险，包括可能的不良反应和严重程度。
      3. 监测建议：针对该患者的具体情况，提出个性化的监测方案和指标。
      4. 处理措施：提供具体的临床处理建议，包括剂量调整、给药时间安排等，需特别考虑患者的肝肾功能状态。
      5. 药物替换：提供可能的替代药物选项，并说明选择理由，特别关注患者的过敏史和器官功能状态。
      
      请确保分析内容高度个性化，充分考虑患者的个体特征，而不仅仅是提供通用的药物相互作用信息。
    `.replace(/^\s+/gm, '').trim()
    
    // 调用AI服务进行分析
    const aiAnalysis = await analyzeDrugInteractionWithSparkHttp(
      interaction.drugs[0],
      interaction.drugs[1],
      prompt,
      {
        model: 'pro'
      }
    )
    
    // 更新交互对象的AI分析结果
    interaction.aiAnalysis = aiAnalysis
  } catch (error) {
    console.error('AI分析出错:', error)
    interaction.aiAnalysis = 'AI分析失败: ' + (error instanceof Error ? error.message : '未知错误')
  } finally {
    // 取消加载状态
    interaction.aiAnalysisLoading = false
  }
}

const printReport = () => {
  window.print()
}

const exportReport = () => {
  alert('导出PDF功能将在后续版本中实现')
}

// 翻译描述
const translateDescription = async (interaction: any) => {
  if (!interaction.description) return;
  
  interaction.translating = true;
  try {
    const translated = await tencentTranslateService.translateText(interaction.description, 'zh');
    interaction.translatedDescription = translated;
  } catch (error) {
    console.error('翻译描述出错:', error);
    interaction.translatedDescription = '翻译失败';
  } finally {
    interaction.translating = false;
  }
}

// 翻译建议
const translateRecommendation = async (interaction: any) => {
  if (!interaction.recommendation) return;
  
  interaction.translating = true;
  try {
    const translated = await tencentTranslateService.translateText(interaction.recommendation, 'zh');
    interaction.translatedRecommendation = translated;
  } catch (error) {
    console.error('翻译建议出错:', error);
    interaction.translatedRecommendation = '翻译失败';
  } finally {
    interaction.translating = false;
  }
}
</script>

<style scoped>
.doctor-review {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.doctor-review h1 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 2rem;
}

.review-info {
  background-color: #e3f2fd;
  padding: 25px;
  border-radius: 10px;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  text-align: center;
}

.review-info p {
  color: #2c3e50;
  font-size: 1.1rem;
  margin: 0;
}

.report-section {
  background-color: #f8f9fa;
  padding: 25px;
  border-radius: 10px;
  margin-bottom: 30px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.08);
}

.report-section h2 {
  margin-top: 0;
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 10px;
  font-size: 1.6rem;
}

.report-content {
  margin-top: 20px;
}

.report-content ul {
  padding-left: 25px;
}

.report-content li {
  margin-bottom: 15px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  border-left: 4px solid #3498db;
}

.report-content p {
  margin: 10px 0;
  color: #555;
  font-size: 1rem;
  line-height: 1.5;
}

.report-content strong {
  color: #2c3e50;
}

.interaction-item {
  background-color: white;
  padding: 25px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  border-left: 5px solid #ddd;
}

.interaction-item.risk-high {
  border-left-color: #e74c3c;
}

.interaction-item.risk-medium {
  border-left-color: #f39c12;
}

.interaction-item.risk-low {
  border-left-color: #27ae60;
}

.interaction-item h3 {
  margin-top: 0;
  color: #2c3e50;
  font-size: 1.4rem;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.risk-high {
  color: #e74c3c;
  font-weight: bold;
}

.risk-medium {
  color: #f39c12;
  font-weight: bold;
}

.risk-low {
  color: #27ae60;
  font-weight: bold;
}

.not-analyzed {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff3e0;
  border-radius: 8px;
  color: #f57c00;
  text-align: center;
  font-weight: 500;
}

.ai-analysis-result {
  margin-top: 25px;
  padding: 25px;
  background-color: #e3f2fd;
  border-radius: 8px;
  border-left: 4px solid #1976d2;
}

.ai-analysis-result h4 {
  margin-top: 0;
  color: #2c3e50;
  font-size: 1.3rem;
  border-bottom: 1px solid #bbdefb;
  padding-bottom: 10px;
}

.translation-section {
  margin: 20px 0;
  padding: 20px;
  border-left: 4px solid #42b983;
  background-color: #f1f8ff;
  border-radius: 0 8px 8px 0;
}

.translate-btn {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  font-weight: 500;
  margin-top: 15px;
  transition: background-color 0.3s;
}

.translate-btn:hover:not(:disabled) {
  background-color: #2980b9;
}

.translate-btn:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.translated-text {
  margin-top: 15px;
  padding: 15px;
  background-color: #e3f2fd;
  border-radius: 6px;
  font-size: 1rem;
  color: #2c3e50;
}

.action-buttons {
  text-align: center;
  margin-top: 40px;
  padding: 30px 0;
  border-top: 1px solid #eee;
}

.print-btn, .export-btn {
  background-color: #27ae60;
  color: white;
  border: none;
  padding: 14px 28px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 15px;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.print-btn:hover, .export-btn:hover {
  background-color: #219653;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0,0,0,0.15);
}

@media print {
  .action-buttons {
    display: none;
  }
  
  .doctor-review {
    padding: 0;
  }
}

@media (max-width: 768px) {
  .doctor-review {
    padding: 20px;
  }
  
  .report-content li {
    padding: 12px;
  }
  
  .interaction-item {
    padding: 20px;
  }
  
  .action-buttons {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }
  
  .print-btn, .export-btn {
    width: 100%;
    margin: 0;
    padding: 12px;
  }
}
</style>